/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.TurnoProceso;
import dp1.titandevelop.titano.persistent.Turno;
import dp1.titandevelop.titano.service.ProcesoService;
import dp1.titandevelop.titano.view.logist.*;
import dp1.titandevelop.titano.service.TurnoService;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Yulian
 */
public class ModulosT_PRO_OPDetalle extends javax.swing.JDialog {
    
    //Para el cbox
    private TurnoProceso procesos;
    private List<Turno> turnos;
    private ArrayList<Integer> comprobarturnos;
    private int cantturnos;
   
    //Para agregar elementos al cbox    
    private void addList (List<Turno> lista){
        for(int i=0;i<lista.size();i++){
            this.cmbturno.addItem(lista.get(i).getDescripcion());
        }
    }
     public void RefreshTable() {
        AbstractTableModel aux = (AbstractTableModel)tblDetalle.getModel();
        aux.fireTableDataChanged();
    }
    public ModulosT_PRO_OPDetalle(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = this.getSize();
        this.setLocation((desktopSize.width - jInternalFrameSize.width-20),
                (desktopSize.height - jInternalFrameSize.height)/6);
        
        ProcesoService serv = new ProcesoService();
        TurnoService tur = new TurnoService();
        procesos = new TurnoProceso();
        //para el combo box
        turnos = tur.buscarTurnos();
        addList(turnos);
        
        //se llena la tabla
        this.tblDetalle.setModel(modeloTabla);
        //para comprobar que no se repitan los turnos
        
        cantturnos = turnos.size();
        comprobarturnos = new ArrayList<Integer>();
             
        
    }

    private AbstractTableModel modeloTabla = new AbstractTableModel() {  
        
        private String [] titles = {"Proceso","Productividad","Merma"};
        @Override
        public int getRowCount() {
            return procesos.getProcesos().size();//tipos.size(); // cuantos registros (filas)
        }      
        @Override
        public int getColumnCount() {
            return 3; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            
            Object res=null;
            //boolean b = datos.get(rowIndex).seleccionado;//tipos.get(rowIndex);
            switch(columnIndex){
                case 0: res = procesos.getProcesos().get(rowIndex).getDescripcion();break;
                case 1: res = procesos.getProductividades().get(rowIndex); break;
                case 2: res = procesos.getMermas().get(rowIndex) ; break;
            }
            return res;
        } 
        @Override
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            switch(columnIndex){
//                case 0: res = p.getDescripcion();break;
                case 1: procesos.getProductividades().set(rowIndex,((Integer)value).intValue()); break;
                case 2: procesos.getMermas().set(rowIndex, ((Integer)value).intValue()) ; break;
            }
        } 
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean res=false;
            switch (col) {
                case 0:break;
                case 1: res = true; break;
                case 2: res = true; break;
            }
            return res;
        }
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    };
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnOk = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblDetalle = new javax.swing.JTable();
        cmbturno = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/asignar.png"))); // NOI18N
        btnOk.setToolTipText("Agregar");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Insumos"));

        tblDetalle.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Proceso", "Productividad", "Merma"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblDetalle.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblDetalleMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblDetalle);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 381, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
        );

        cmbturno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione" }));
        cmbturno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbturnoActionPerformed(evt);
            }
        });

        jLabel1.setText("Turno");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnOk)
                        .addGap(1, 1, 1)
                        .addComponent(btnCancelar)))
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbturno, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbturno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnOk)
                    .addComponent(btnCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 21, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        Boolean salir = false;
        Boolean repetido = false;
        this.RefreshTable();
        //para el primer turno que se agrega:
       if (this.cmbturno.getSelectedIndex()-1==-1){
       } else{
           int idturno = turnos.get(this.cmbturno.getSelectedIndex()-1).getIdturno();
        if (comprobarturnos.isEmpty()){
            comprobarturnos.add(idturno);
        }else{ // si no es el primer turnno entonces se comprueba que ya no se hayan ingresado todos los turnos
            if (comprobarturnos.size() == cantturnos){
                salir = true;
            }else {//se agrega.. pero ojo, se debe comprobar que ya no se ingreso el id sino ya no psss
                for (int i =0; i<comprobarturnos.size();i++){
                    if (comprobarturnos.get(i)== idturno){
                        repetido = true;
                    }else {
                        
                    }
                }               
            }
        }
        
        //entonces ahora si se agrega
        if (salir){
            this.dispose();
        }else {
            if (repetido){
            }else{
                
                for (int i = 0 ; i<procesos.getProcesos().size();i++){
                    if (procesos.getProductividades().get(i)== 0 && procesos.getMermas().get(i)== 0){
                     
                    }else {
                        ModulosT_PRO.ventanaNuevoOp.addidTurno(idturno);
                        ModulosT_PRO.ventanaNuevoOp.addidProcesos(procesos.getProcesos().get(i).getIdproceso());
                        ModulosT_PRO.ventanaNuevoOp.addProduct(procesos.getProductividades().get(i));
                        ModulosT_PRO.ventanaNuevoOp.addMerma(procesos.getMermas().get(i)) ; 
                        comprobarturnos.add(idturno);
                        
                    }
                }
                ModulosT_PRO.ventanaNuevoOp.RefreshTable();
            }
        }
        
       } 
    }//GEN-LAST:event_btnOkActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tblDetalleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblDetalleMouseClicked

    }//GEN-LAST:event_tblDetalleMouseClicked

    private void cmbturnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbturnoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbturnoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ModulosT_PRO_OPNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ModulosT_PRO_OPNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ModulosT_PRO_OPNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ModulosT_PRO_OPNuevo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ModulosT_LOG_APDetalle dialog = new ModulosT_LOG_APDetalle(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnOk;
    private javax.swing.JComboBox cmbturno;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblDetalle;
    // End of variables declaration//GEN-END:variables
}
